<template>
  <el-dialog
    v-bind.sync="$attrs"
    destroy-on-close
    :before-close="cancel"
    :visible.sync="isShowAddGoods"
  >
    <el-form
      ref="elForm_goods"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="100px"
    >
      <el-form-item label="商品类型" prop="peerType">
        <el-radio-group v-model.number="formData.peerType" size="medium">
          <el-radio
            v-for="(item, index) in dict.type.activity_goodsType"
            :key="index"
            :label="parseInt(item.value)"
            @change="peerTypeChange"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <!-- 优惠券 -->
      <el-form-item
        label="优惠券"
        prop="couponId"
        v-if="formData.peerType == 1"
      >
        <el-select
          v-model="formData.couponId"
          placeholder="请选择优惠券"
          @change="couponChange"
          clearable
          :style="{ width: '100%' }"
        >
          <el-option
            v-for="(item, index) in businessIdOptions"
            :key="index"
            :label="item.businessName"
            :value="item.businessId"
            style="
              max-width: 500px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;"
            :title='item.businessName'
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="peerName">
        <el-input
          v-model.trim="formData.peerName"
          :disabled="formData.peerType == 1"
          placeholder="请输入名称"
          :maxlength="50"
          show-word-limit
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item label="优惠券库存" prop="total" v-if="formData.peerType == 1">
        <el-input
          v-model="formData.total"
          :disabled="true"
           placeholder="请输入优惠券库存"
          :style="{ width: '100%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="奖品库存" prop="peerStock">
        <el-input
          v-model.trim="formData.peerStock"
          type="input"
          placeholder="请输入奖品库存数"
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item label="组队人数" prop="peerNumber">
        <el-input
          v-model="formData.peerNumber"
          placeholder="请输入组队人数"
          :style="{ width: '100%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="赠送人数" prop="peerGive">
        <el-input
          v-model="formData.peerGive"
          placeholder="请输入赠送人数"
          :style="{ width: '100%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label="实物照片"
        prop="peerUrl"
        required
        v-if="formData.peerType != 1"
      >
        <MmvUploadImage @upImg="uppeerImage" ref="peerUrl" size="2">
          <el-button size="small" type="primary" icon="el-icon-upload"
            >添加图片</el-button
          >
          <div slot="tip" class="el-upload__tip">
            支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，仅限1张图片
          </div>
        </MmvUploadImage>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { couponBusActivityList } from '@/api/activity/seckill'
import MmvUploadImage from '../components/mmv-upload-image.vue'
export default {
  components: { MmvUploadImage },
  props:{
    activitySeckillList: {
      type: Array,
      default: [],
    },
  },
  dicts: ['activity_goodsType'],
  data() {
    // 验证组队人数的规则
    var checkPeerNumber = (rule, value, callback) => {
      if (this.formData.peerGive && value < this.formData.peerGive) {
        callback(new Error('组队人数应大于或等于赠送人数'))
      } else if (value < 2) {
        callback(new Error('组队人数应大于或等于2'))
      } else {
        this.$refs['elForm_goods'].clearValidate('peerGive')
        return callback()
      }
    }
    // 验证赠送人数的规则
    var checkPeerGive = (rule, value, callback) => {
      if (this.formData.peerNumber && value > this.formData.peerNumber) {
        callback(new Error('赠送人数应小于或等于组队人数'))
      }
      this.$refs['elForm_goods'].clearValidate('peerNumber')
      return callback()
    }
    var maxNumber = (rule, value, callback) => {
           if (value&&this.formData.peerType == 1&& value> this.formData.total) {
            callback(new Error('优惠券数量不能大于库存数量!'));
          } else {
            callback();
          }
     };
    return {
      //新增与编辑标识
      index: null,
      //优惠券列表数据
      businessIdOptions: [],
      isShowAddGoods: false,
      formData: {
        peerType: 1,
        couponId: null,
        businessName: null,
        peerName: '',
        peerUrl: '',
        peerNumber: null,
        peerGive: null,
        peerStock: null,
        total:0
      },
      rules: {
        peerType: [
          {
            required: true,
            message: '请选择商品类型',
            trigger: 'change',
          },
        ],
        couponId: [
          {
            required: true,
            message: '请选择优惠券',
            trigger: 'change',
          },
        ],
        peerName: [
          {
            required: true,
            message: '请输入商品实物名称',
            trigger: 'blur',
          },
        ],
        peerNumber: [
          {
            required: true,
            message: '请输入组队人数',
            trigger: 'blur',
          },
          { validator: checkPeerNumber, trigger: 'blur' },
          {
            required: true,
            pattern: /^([1-9]\d*)$/,
            message: '只能输入正整数',
            trigger: 'blur',
          },
        ],
        peerGive: [
          {
            required: true,
            message: '请输入赠送人数',
            trigger: 'blur',
          },
          { validator: checkPeerGive, trigger: 'blur' },
          {
            pattern: /^([1-9]\d*)$/,
            message: '只能输入正整数',
            trigger: 'change',
          },
        ],
        peerUrl: [
          {
            required: true,
            message: '请选择实物照片',
            trigger: 'blur',
          },
        ],
        peerStock: [
          {
            required: true,
            message: '请输入奖品库存数',
            trigger: 'blur',
          },
          {
            pattern: /^([1-9]\d*)$/,
            message: '只能输入正整数',
            trigger: 'change',
          },
          { validator: maxNumber, trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    // 商品类型变化
    peerTypeChange(val) {
      this.formData = {
        peerType: val,
        couponId: null,
        businessName: null,
        peerName: '',
        peerNumber: null,
        peerUrl: '',
        peerGive: null,
        peerStock: null,
      }
      this.$refs['elForm_goods'].resetFields('peerName')
      this.rules.peerUrl[0].required = peerUrl != 1 ? true : false
    },
    //优惠券变化
    couponChange(val) {
      if (this.formData.peerType == 1) {
        let data = this.businessIdOptions.filter((e) => {
          return val == e.businessId
        })[0]
        this.formData.peerName = data.couponName
        this.formData.total = data.total
      }
    },
    // 添加实物图片
    uppeerImage(url) {
      // 分享封面上传成功地址
      this.formData.peerUrl = url[0]
      this.$refs['elForm_goods'].validateField('peerUrl')
    },
    businessIdChange(val) {
      if (this.formData.peerType == 1 && val) {
        this.formData.peerName = this.businessIdOptions.filter((e) => {
          return val == e.businessId
        })[0].couponName
      }
    },
    // 获取优惠券列表
    couponBusActivityList(data) {
      couponBusActivityList().then((res) => {
        let editId;
        if(data&&data.row){
            editId=data.row.couponId
        }
        let arr=this.activitySeckillList.map(e=>{
          return e.couponId;
        })
        this.businessIdOptions = res.rows.filter((e) => {
          return  arr.indexOf(e.businessId) <0 || e.businessId==editId
        })
        this.formData = {
          peerType: 1,
          couponId: null,
          businessName: null,
          peerName: '',
          peerUrl: '',
          peerNumber: null,
          peerGive: null,
          peerStock: null,
        }
        if (data.type !== null) {
          this.index = data.type
          this.formData = data.row
          this.businessIdChange(this.formData.couponId)
          this.$refs.peerUrl.previewToUrl(this.formData.peerUrl)
        } else {
          this.index = null
        }
      })
    },
    submitForm() {
      this.$refs['elForm_goods'].validate((valid) => {
        if (!valid) {
          return false
        } else {
          // TODO 提交表单
          this.$emit('submit', { index: this.index, row: this.formData })
          this.isShowAddGoods = false
        }
      })
    },
    resetForm() {
      this.$nextTick(() => {
        this.$refs.elForm_goods.resetFields()
      })
    },
    show(data) {
      this.isShowAddGoods = true
      this.resetForm()
      this.couponBusActivityList(data)
    },
    // 取消按钮
    cancel() {
      this.isShowAddGoods = false
      this.resetForm()
      this.$emit('close')
    },
  },
}
</script>
<style>
</style>
